import BImage from '../skin/component/bimage';
import Component from './uicomponent';
const CLASS_MAP = {
    Image:1,
    BImage:1,
    Group:PIXI.Container,
    Button:PIXI.Gown.Button,
    CheckButton:PIXI.Gown.CheckBox,
    RatioButton:PIXI.Gown.RadioButton,
    ToggleButton:PIXI.Gown.ToggleButton,
    RatioGrup:PIXI.Gown.ToggleGroup,
    List:PIXI.Gown.List,
    TextInput:PIXI.Gown.TextInput,
    Scroller:PIXI.Gown.Scroller,
    Label:PIXI.Text,
    Sprite:PIXI.Sprite,
    Sprite9:PIXI.NineSlicePlane,
    BitmapLabel:PIXI.BitmapText,
    // 水平布局
    Horizontallayout:PIXI.Gown.HorizontalLayout,
    // 垂直布局
    Verticallayout:PIXI.Gown.VerticalLayout,
    // tiled 垂直布局
    Tiledrowslayout:PIXI.Gown.TiledRowsLayout,
    // tiled 水平布局
    Tiledcolumnslayout:PIXI.Gown.TiledColumnsLayout,
}

// 创建皮肤
exports.createSkin = function(config) {
    let skin = {
        width:config.width, 
        height:config.height, 
        minWidth:config.minWidth,
        minHeight:config.minHeight,
        ctrname:config.ctrname,
        children:[],
        states:{},
        idMap:{}
    } 
    let elements = skin.children;
    let states = skin.states;
    let idMap = skin.idMap;
    let childrenName = "children";
    var len = config[childrenName] ? config[childrenName].length : 0;
    var j = 0;
    for (var i = 0; i < len; i++) {
        var element = createElement(config[childrenName][i], idMap);
        if (!element) {
            console.error("生成皮肤错误:", config[childrenName][i])
        } else {
            elements[j++] = element;
        }
    }
    return skin;
}

// 创建元素
function createElement(config, idMap) {
    var nodeName = config["node"];
    var children = config["children"];
    
    var item = null;
    if (nodeName == "Image") {
        item = createSprite(config)
    } else if (nodeName == "BImage") {
        item = createBImage(config)
        return item;
    } else if (nodeName == "Label") {
        item = createLabel(config)
    } else if (nodeName == "BitmapLabel") {
        item =  crateBitmapLabel(config)
    } else if (nodeName == "ProgressBar") {
        console.log("进度条功能还未实现")
    } else if (nodeName == "Scroller") {
        item = createScroller(config);
    } else if (nodeName == "List") {
        item = createList(config);
    } else if (nodeName == "Group") {
        var nodeC = getClassByName(nodeName);
        if (nodeC) {
            item = new nodeC();
            mixinProp(config, item, {"children":1, "node":1});
            var len = children ? children.length : 0;
            for (var i = 0; i < len; i++) {
                var subConfig = config["children"][i];
                let subItem = createElement(subConfig, idMap);
                item.addChild(subItem)
            }
        }
    } else {
        console.error("不能非法解析类:", nodeName)
    }

    if (item) {
        if (item.position) {
            if (config.x) {
                item.position.x = config.x;
            }
            if (config.y) {
                item.position.y = config.y
            }
        }
        if (item.anchor) {
            if (config.anchorX) {
                item.anchor.x = config.anchorX;
            }
            if (config.anchorY) {
                item.anchor.y = config.anchorY;
            }
        }
        if (item.scale) {
            if (config.scaleX) {
                item.scale.x = config.scaleX;
            }
            if (config.scaleY) {
                item.scale.y = config.scaleY;
            }    
        }
        if (config.id) {
            if (!idMap[config.id]) {
                idMap[config.id] = item;
            } else {
                console.error("不能有重复的id:",config.id)
            }
        }
    }
    return item;
}

// 给节点附值
function mixinProp(source, target, except) {
    let keys = Object.keys(source);
    for (let i = 0; i < keys.length; i++) {
        let key = keys[i]
        if (except && except[key]) {

        } else {
            let value = source[key];
            target[key] = value;
        }
    }
}

// 通过名字得到类
function getClassByName(name) {
    if (!name) {
        throw new Error("不能得到空内容的类名")
    }
    let c = CLASS_MAP[name] || window[name];
    if (!c) {
        console.error("无法得到类", name)
    }
    return c;
}

//----------------------创建sprite-------------------------------
function createSprite(item) {
    let key = item.src ? item.src.replace("_png", ".png") : "";
    let sprite;
    if (item.scale9) {
        let [left, top, right, bottom] = item.scale9;
        sprite = new PIXI.NineSlicePlane(PIXI.Texture.from(key), left, top, right, bottom);
    } else {
        sprite = PIXI.Sprite.from(key);
    }
    if (item.width) {
        sprite.width = item.width;
    }
    if (item.height) {
        sprite.height = item.height;
    }
    return sprite;
}

//-----------------------创建label-------------------------------
function createLabel(item) {
    let text = item.text || "";
    let style = item.style || null;
    let label = new PIXI.Text(text, style);
    return label;
}

//---------------------创建simplebutton
function createBImage(item) {
    let key = item.src ? item.src.replace("_png", ".png") : "";
    let scale9 = item.scale9;
    let sprite = BImage.from(key, scale9)
    if (item.width) {
        sprite.width = item.width;
    }
    if (item.height) {
        sprite.height = item.height;
    }
    sprite.position.x = item.x || 0;
    sprite.position.y = item.y || 0;
    let width = sprite.width;
    let height = sprite.height;
    sprite.anchor.set(0.5, 0.5);
    sprite.position.x += width * 0.5;
    sprite.position.y += height * 0.5;
    return sprite;
}


function crateBitmapLabel() {

}

function createScroller(item) {
    let viewPort = createElement(item.target || item.viewPort);
    let scroller = new PIXI.Gown.Scroller();
    scroller.viewPort = viewPort;
    scroller.x = item.x;
    scroller.y = item.y;
    scroller.width = item.width;
    scroller.height = item.height;
    return scroller;
}

function createList(item) {
    function createListItem() {
        let component = new Component();
        component.setSkin(item.itemRenderer);
        return component;
    }

    let list = new PIXI.Gown.List({});
    let array = item.dataProvider;
    list.dataProvider = new PIXI.Gown.ListCollection(array);
    list.itemRendererFactory = createListItem;
    list.width = +item.width;
    list.height = +item.height;
    list.allowMultipleSelection = false;
    list.x = item.x || 0;
    list.y = item.y || 0;
    return list;
}

// 创建dataprovider
function createArrayColleciton(config) {
    var len = config["children"] ? config["children"].length : 0;
    if (!len) {
        return new PIXI.Gown.ListCollection();
    } else {
        var array = [];
        if (config["children"][0] && config["children"][0]["children"]) {
            var subLen = config["children"][0]["children"].length;
            for (var i = 0; i < subLen; i++) {
                var subConfig = config["children"][0]["children"][i];
                var nodeName = subConfig[NODE_NAME];
                var C = getClassByName(nodeName);
                if (C) {
                    var item = new C();
                    mixinProp(subConfig, item);
                    array.push(item);
                }
            }
        }
        return new PIXI.Gown.ListCollection(array);
    }
}

// 创建布局
function createLayout(config) {
    let subConfig = config["children"][0];
    var node = subConfig["node"];
    var c = CLASS_MAP[node];
    if (c) {
        var layout = new c();
        mixinProp(config, layout);
        return layout;
    } else {
        console.error("没有注册类:", node);
    }
}
